<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/page/include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>选择图片</title>
    <link href="${ctxStatic}/layui-v2.2.45/layui/css/layui.css" rel="stylesheet"/>
    <link rel="stylesheet" href="${ctx}/css/common/common.css">
    <link href="${ctx}/css/ui/resource/selImg.css" rel="stylesheet"/>
</head>
<body>
<div class="sel-img-panel">
    <div class="upload-content">
        <form id="form">
            <input type="file" id="upload_input" class="u-single-file dn"
                   accept="image/gif,image/png,image/jpg,image/jpeg" multiple>
        </form>
        <button class="layui-btn layui-btn-danger" id="upload_btn">本地上传</button>
        <span class="infos gray"></span>
        <div class="upload-list-content" style="display: none">
            <ul class="upload-list" id="progress_list">
            </ul>
        </div>
    </div>
    <hr class="panel-split">
    <div class="list-content sel-ctn">
        <ul class="img-list"></ul>
    </div>
</div>
<script type="text/javascript" src="${ctxStatic}/jquery/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="${ctxStatic}/layui-v2.2.45/layui/layui.js"></script>
<!-- build:js -->
<script type="text/javascript" src="${ctx}/script/common/common.js"></script>
<script type="text/javascript" src="${ctx}/script/common/util.js"></script>
<!-- endbuild -->
<script type="text/javascript" src="${ctxStatic}/cos-js-sdk-v4-master/dist/cos-js-sdk-v4.js"></script>
<script src="${ctxStatic}/exif/exif.js"></script>
<script src="${ctxStatic}/lrz/lrz.bundle.js"></script>
<script src="${ctx}/script/upload/cosUploadUtil.js"></script>
<script>
    var element, layer, cosUtil, mainApp;
    $(function () {
        layui.use(['element', 'layer'], function () {
            element = layui.element;
            layer = layui.layer;
        });
        cosUtil = new CosUtil({
            mainFolder: '/${sessionScope.newCurrentUser.id}/image/',
            imgCompress: '${compress}',
            onSelect: function (files) {
                var that = this;
                var filterFiles = [], now = new Date();
                for (var i = 0, file; file = files[i]; i++) {
                    var fileName = file.name;
                    file.id = now.getTime() + i;
                    file.suffix = fileName.substring(fileName.lastIndexOf('.'))
                    filterFiles.push(file);
                    $('#progress_list').append(mainApp.getProgressTpl(file, '1%'));
                }
                mainApp.saveFiles = [];
                $('#progress_list').parent().show();
                cosUtil.uploadImg(filterFiles);
            },
            onSuccess: function (file, ret) {
                var that = this;
                var data = ret.data;
                var shootDate = file.exif.DateTimeOriginal ? (Date.parse(file.exif.DateTimeOriginal.split(' ')[0].replace(/:/g, "/")+' '+file.exif.DateTimeOriginal.split(' ')[1])):''
                mainApp.saveFiles.push({
                    name: file.name,
                    suffix: file.suffix,
                    createBy: '${sessionScope.newCurrentUser.id}',
                    type: mainApp.bizType,
                    path: data.resource_path,
                    width: file.width,
                    ratio: file.ratio,
                    size: file.resizeSize || file.size,
                    shootTime: shootDate,
                    cameraType: (file.exif.Make ? file.exif.Make.trim().replace(/\0/g, '') : '') + (file.exif.Model ? (' ' + file.exif.Model.trim().replace(/\0/g, '')) : '')
                });
            },
            onProgress: function (file, ret) {
                console.log('onProgress', arguments);
                if (ret < 1) {
                    element.progress('progress_' + file.id, parseInt(ret * 100) + '%');
                } else {
                    element.progress('progress_' + file.id, '100%');
                    setTimeout(function () {
                        $('#progress_' + file.id).remove();
                    }, 1000);
                }
            },
            onFailure: function () {

            },
            onComplete: function () {
                $('#progress_list').parent().hide();
                mainApp.saveImgs();
            }
        }).init();
        mainApp = {
            listContext: '',
            page: 1,
            pageSize: 24,
            noMoreData: false, // 用于判断列表是否还有数据
            dataBack: true,// 列表异步数据是否已经返回，用于阻塞scroll事件
            saveFiles: [],
            min: '${min}' || 1, // 至少选择图片数
            max: '${max}' || 100,// 最多可选图片数
            bizType: '${type}',//业务类型
            selIds: {},
            selCount: 0,
            // 获取用户图片目录
            getFolderList: function () {
                var that = this;
                // cosUtil.cos.getFolderList(function (ret) {
                //     if (!ret.data.listover) { // 还有下一页
                //         that.listContext = ret.data.context;
                //     }
                //     for (var i = 0; i < ret.data.infos.length; i++) {
                //         var item = ret.data.infos[i], resource_path = item.source_url.replace('http://', '');
                //         resource_path = '/' + cosUtil.opt.appid + '/' + cosUtil.opt.bucket + resource_path.substring(resource_path.indexOf('/'));
                //         $('.img-list').prepend(mainApp.getImgTpl({
                //             source_url: item.source_url,
                //             resource_path: resource_path
                //         }));
                //     }
                // }, function (err) {
                //
                // }, cosUtil.opt.bucket, cosUtil.opt.mainFolder, that.pageSize, that.listContext, 1);
                mainApp.dataBack = false;
                txz.ajaxRequest({
                    url: '${ctx}/file/img/api/list.do',
                    params: {
                        createBy: '${sessionScope.newCurrentUser.id}',
                        pageNo: that.page,
                        limit: that.pageSize
                    },
                    callBack: function (ret) {
                        mainApp.dataBack = true;
                        if (!ret.page.hasNextPage) {
                            mainApp.noMoreData = true;
                        }
                        if (that.page === 1) {
                            $('.img-list').html('');
                        }
                        for (var i = 0; i < ret.data.length; i++) {
                            var item = ret.data[i], resource_path = item.path;
                            var iAppid = resource_path.split('/')[1], iBucket = resource_path.split('/')[2];
                            var source_url ='http://'+iBucket+'-'+iAppid+'.cos'+cosUtil.opt.region+'.myqcloud.com' + resource_path.replace('/' + iAppid + '/' + iBucket, '');
                            item.source_url = source_url;
                            item.resource_path = resource_path;
                            $('.img-list').append(mainApp.getImgTpl(item));
                        }
                    }
                })
            },
            getImgTpl: function (item) {
                var resource_path = item.path, iAppid = resource_path.split('/')[1], iBucket = resource_path.split('/')[2];
                var cdnPath ='http://'+iBucket+'-'+iAppid+'.image.myqcloud.com' + resource_path.replace('/' + iAppid + '/' + iBucket, '');
                var style = (item.ratio && parseFloat(item.ratio) < 1) ? 'width: 114px' : 'height:114px';
                var tpl = '<li class="img-item ' + (mainApp.selIds[item.id] ? 'selected' : '') + '" data-url="' + cdnPath + '" data-w="' + item.width + '" data-r="' + item.ratio + '" data-id="' + item.id + '">\n' +
                    '    <div class="pic-box">\n' +
                    '        <img class="pic" src="' + item.source_url + '" alt="" style="' + style + '">\n' +
                    '        <div class="status-mask">\n' +
                    '            <div class="sel-inner"><i class="iconfont icon-check"></i></div>\n' +
                    '        </div>\n' +
                    '    </div>\n' +
                    '     <div class="pic-name ellipsis-1">' + item.name + '</div>' +
                    '</li>';
                return tpl;
            },
            getProgressTpl: function (file, persent) {
                var tpl = ' <li class="upload-item" id="progress_' + file.id + '">\n' +
                    '     <div class="upload-name ellipsis-1">' + file.name + '</div>\n' +
                    '     <div class="upload-progress">\n' +
                    '         <div class="layui-progress" lay-filter="progress_' + file.id + '">\n' +
                    '             <div class="layui-progress-bar layui-bg-red" lay-percent="' + persent + '"></div>\n' +
                    '         </div>\n' +
                    '     </div>\n' +
                    ' </li>'
                return tpl;
            },
            // 入库
            saveImgs: function () {
                var that = this;
                txz.ajaxRequest({
                    url: '${ctx}/file/img/api/save.do',
                    params: {
                        imgs: JSON.stringify(that.saveFiles)
                    },
                    callBack: function (ret) {
                        if (ret.success) {
                            mainApp.page = 1;
                            mainApp.noMoreData = false;
                            mainApp.getFolderList();
                            console.log('入库成功');
                        } else {
                            console.error('入库失败');
                        }
                    }
                })
            },
            init: function () {
                txz.toBtmListener(function (ret) {
                    if (!mainApp.noMoreData && mainApp.dataBack) {
                        ++mainApp.page;
                        mainApp.getFolderList();
                    }
                }, 100);
                mainApp.getFolderList();
                $('#upload_btn').on('click', function () {
                    $('#upload_input').off('change').on('change', function (e) {
                        cosUtil.opt.onSelect(e.target.files);
                        $('#form')[0].reset();
                        return false;
                    });
                    setTimeout(function () {
                        $('#upload_input').click();
                    }, 0);
                    return false;
                });
                $('.img-list').on('click', '.img-item', function (e) {
                    var $item = $(this);
                    if ($item.hasClass('selected')) {
                        $item.removeClass('selected');
                        delete mainApp.selIds[$item.data('id')];
                        --mainApp.selCount;
                    } else {
                        if (mainApp.selCount === parseInt(mainApp.max)) {
                            util.layerMsgError('最多只能选择' + mainApp.max + '张图片');
                            return;
                        }
                        $item.addClass('selected');
                        mainApp.selIds[$item.data('id')] = true;
                        ++mainApp.selCount;
                    }
                });
                $('.infos').text('${info}' || '');
            }
        };
        mainApp.init();
    })

    function validate() {
        if (mainApp.selCount < parseInt(mainApp.min)) {
            util.layerMsgError('请至少选择' + mainApp.min + '张图片');
            return false;
        }
        return true;
    }

    function close() {
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.close(index);
    }

    function getImgs() {
        var selImgs = [];
        for (var attr in mainApp.selIds) {
            var $item = $('.img-item[data-id=' + attr + ']');

            function getHtmlStr(item) {
                var str = '';
                if (item.width <= 100) {
                    str = '<img data-width="' + item.width + '" data-ratio="' + item.ratio + '" src="' + item.path + '" />';
                } else {
                    var _w = item.width;
                    if (item.width > 750) {
                        _w = 750;
                    }
                    str = '<img width="' + _w + '" data-width="' + item.width + '" data-ratio="' + item.ratio + '" src="' + item.path + '" />';
                }
                return str;
            }

            var file = {
                path: $item.data('url'),
                width: $item.data('w'),
                ratio: $item.data('r'),
                id: $item.data('id')
            }
            file.htmlStr = getHtmlStr(file);
            selImgs.push(file);
        }
        return selImgs;
    }
</script>
</body>
</html>